package com.glureau.aib.server.auth;

import org.mindrot.jbcrypt.BCrypt;
import org.mortbay.jetty.security.Credential.MD5;

import com.glureau.aib.client.auth.LoginService;
import com.glureau.aib.server.db.mysql.DB_Login;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class LoginServiceImpl extends RemoteServiceServlet implements
		LoginService {

	@Override
	public String connect(String login, String password) {
		DB_Login loginDAO = new DB_Login();
		String dbPasswd = loginDAO.getHashPassword(login);
		String sessionID = null;
		boolean failed = true;

		if (dbPasswd != null) {
			boolean valid = BCrypt.checkpw(password, dbPasswd);
			if (valid) {
				sessionID = generateSessionID(dbPasswd);
				int userID = loginDAO.getUserId(login);
				loginDAO.addConnexion(sessionID, userID);
				failed = false;
			}
		}
		if (failed) {
			throw new IllegalArgumentException("Login/Password are wrong.");
		}
		return sessionID;
	}

	private String generateSessionID(String hashPassword) {
		return MD5.digest(hashPassword + System.currentTimeMillis()).substring(4);
	}

	@Override
	public void addUser(String email, String login, String passwd) {
		DB_Login loginDAO = new DB_Login();
		loginDAO.createUser(email, login, passwd);
	}

	@Override
	public boolean checkSession(String sessionID) {
		DB_Login loginDAO = new DB_Login();
		return loginDAO.checkSession(sessionID);
	}

}
